var url = "";
var aypId = "";
var sectionId = "";
var planStatus = "";
var curriculamArr = new Array();
var gradeArr = new Array();
var ceGradeIdArr = new Array();
var tempArray = new Array();
var displayArr = new Array();
var availableTags = new Array();
var prevGrade = -1;
var teachersIdArr = new Array();
var teachersIdArr1 = new Array();
var valueSelected = false;
var prevValue = "";
var currViewModel = "";
var isHelpActive = false;
var totalAcademicPeriods = 0;

var curriculamModel = function ViewModel() {
	var self = this;

	self.selectedGrade = ko.observable()
	self.sectionTitle = ko.observable();
	self.displayMode = ko.observable(false);
	self.subjects = ko.observableArray();
	self.gradeArr = ko.observableArray(gradeArr);
	self.grade1 = ko.observable("abc");
	self.totalAcademicPeriods = ko.observable();
	self.calcGrade = ko.computed(function() {
		var grade = self.selectedGrade();
		//self.grade1(self.selectedGrade.gradeName);

		if (self.selectedGrade() == undefined) {

			return;
		}
		//console.log("grade1", self.selectedGrade().gradeName);
		self.grade1(self.selectedGrade().gradeName);
		return grade;
	});
	self.clearData = function(s) {
		//alert("cancel");
	}

	self.saveData = function(e, f) {
		//console.log("self.saveData  e, f, this:: ", e, f, this);
		var vm = ko.validation.group(this);
		var isValid = true;

		if (this.isValid() == false) {
			vm.showAllMessages();
			alert("Please fill all Required fields before saving1.");
			return;
		}

		for (var i = 0; i < this.subjects().length; i++) {
			var vm1 = ko.validation.group(this.subjects()[i]);
			//console.log("vm1 - changed:", vm1().length);
			if (vm1().length != 0) {
				isValid = false;
				vm1.showAllMessages();
			}
		}

		if (!isValid) {
			//alert("Please fill all Required fields before saving2.");//Commented By Vikash
			//return;//Commented By Vikash
		}

		//console.log("self.totalPeriods", self.totalPeriods());
		if (self.totalPeriods() > self.totalAcademicPeriods()) {
			//	alert("Total Number of assigned periods are greater than total periods for this grade");
			//var str = "You have exceed the maximum number of allocated periods per week of "+ self.grade1()+". Kindly review the number of periods per week for each subjects. ";
			var str = "You have exceed the maximum number of allocated periods per week (" + self.totalAcademicPeriods() + " periods per week). Kindly review the number of periods per week for each subjects."
			openAlertBox(str)
			return;
		}
		var mapping = {
			'ignore' : ["isSubjectOptional", "selectedGrade", "calcGrade", "gradeArr", "totalPeriods", "totalSessions", "subjectTitle", "ownerTeacherName", "errors", "subType", "hasSubSubjects", "isSubsubject", "filteredTeacherArr", "subsubjectOptionalGroup"]
		}
		var jsonData = ko.mapping.toJSON(self.subjects, mapping);
		saveTempData(this, self.selectedGrade());
		//console.log("BO data for server\n", jsonData);
		//console.log("\n EO data for server");
		showLoader(true, TYPE_SAVING);
		self.displayMode(false);
		saveDataToServer(jsonData);

	}

	self.totalPeriods = ko.computed(function() {
		var t = 0;
		var distinctSubsubjectOptionalGroupArr = new Array();
		var optionalCoCurrSubjectsArr = [];
		/**
		 *optional CoCurrSubject Period Added once
		 */
		var addedOnce = false;
		for (var j = 0; j < self.subjects().length; j++) {

			/**
			 *Prasanna caught 2
			 * total periods
			 */
			var _periodCount = Number(self.subjects()[j].periodPerWeek());
			var _cePeriodCount = Number(self.subjects()[j].cePeriodPerWeek());
			var _labPeriodCount = Number(self.subjects()[j].labPeriodPerWeek());

			var tempPeriodPerWeekArr = new Array();

			for (var a = 0; a < currViewModel.subjects().length; a++) {
				if (currViewModel.subjects()[a].subsubjectOptionalGroup() != 0) {
					tempPeriodPerWeekArr.push(a);
				}
			}

			for (var k = 0; k < tempPeriodPerWeekArr.length; k++) {
				//console.log("----currViewModel.subjects()[j].subsubjectOptionalGroup() :: ", currViewModel.subjects()[j].subsubjectOptionalGroup());
				if (currViewModel.subjects()[j].subsubjectOptionalGroup() == currViewModel.subjects()[tempPeriodPerWeekArr[k]].subsubjectOptionalGroup()) {

					//console.log(" === Periods will tally", currViewModel.subjects()[tempPeriodPerWeekArr[k]].subsubjectOptionalGroup())

					_count = _periodCount + _cePeriodCount + _labPeriodCount;
					_title = currViewModel.subjects()[j].subsubjectOptionalGroup();
					console.log("totalPeriodsCount _title :: ", _title);
					distinctSubsubjectOptionalGroupArr.push({
						title : _title,
						count : _count
					});
					_periodCount = 0;
					_cePeriodCount = 0;
					_labPeriodCount = 0;
				}
			}
			var totalTempPeriod = _periodCount + _cePeriodCount + _labPeriodCount;
			/**
			 * For co curricular subjects optiona add only 1 of then to total Periods.
			 * Prasanna 2014-01-11
			 */

			if (currViewModel.subjects()[j].subType() == 3 && currViewModel.subjects()[j].isSubjectOptional()) {

				optionalCoCurrSubjectsArr.push(currViewModel.subjects()[j]);
				console.log("totalPeriodsCount t, (_periodCount + _cePeriodCount + _labPeriodCount) 1 :: ", t, (_periodCount + _cePeriodCount + _labPeriodCount), currViewModel.subjects()[j].subjectTitle());
				console.log("totalPeriodsCount t, (_periodCount + _cePeriodCount + _labPeriodCount) 2 :: ", t, _periodCount, _cePeriodCount, _labPeriodCount);
				if (addedOnce) {
					totalTempPeriod = 0;
				} else {
					addedOnce = true;
				};

			};

			t = t + totalTempPeriod;

		}

		var _uniquePeriodCntArr = unique(distinctSubsubjectOptionalGroupArr)
		var _addOptionalPeriodCount = 0
		//console.log("distinctSubsubjectOptionalGroupArr", _uniquePeriodCntArr)
		for (var uniqueCntLoop = 0; uniqueCntLoop < _uniquePeriodCntArr.length; uniqueCntLoop++) {
			_addOptionalPeriodCount = +_addOptionalPeriodCount + _uniquePeriodCntArr[uniqueCntLoop].count
			//console.log("totalPeriodsCount _addOptionalPeriodCount :: ", _addOptionalPeriodCount);
		}
		for (var i = 0; i < optionalCoCurrSubjectsArr.length; i++) {
			var sub = optionalCoCurrSubjectsArr[i];

		};
		console.log("totalPeriodsCount t , _addOptionalPeriodCount :: ", t, _addOptionalPeriodCount);
		t = t + _addOptionalPeriodCount;
		//console.log("totalPeriodsCount t :: ", t);

		return Number(t);
	}, this);

	self.backToAcademicYear = function() {

		location.href = url.replace("p_p_state=exclusive", "p_p_state=normal") + "getAcademics";

	}
	//self.gradeArr.subscribe(function(newValue) {
	//console.log("=====");
	//self.gradeArr.sort();
	///});

	self.displayMode.subscribe(function(newValue) {
		//console.log("newValue :: ", newValue);
		if (newValue == true) {
			/**
			 *TODO: Prasanna: Need to remove as it is creating 2 times event for save.
			 * 2014-01-11
			 */

			addclickHandlers(self)
		} else if (newValue == false) {

			removeclickHandlers();
		}
	});

}
function unique(arr) {
	var hash = {}, result = [];
	for (var i = 0, l = arr.length; i < l; ++i) {
		if (!hash.hasOwnProperty(arr[i])) {//it works with objects! in FF, at least
			hash[arr[i]] = true;
			result.push(arr[i]);
		}
	}
	return result;
}

//Convert view to JSON

function viewSubjectDetail(myOptionalStr, subsubjectOptionalGroup, isSubsubject, hasSubSubjects, ceGradeId, subjectId, subjectTitle, aypId, ownerTeacherName, ownerTeacherId, periodPerWeek, cePeriodPerWeek, labPeriodPerWeek, subType) {
	//console.log("ppp myOptionalStr :: ", myOptionalStr, " ::", subjectTitle);
	if (teachersIdArr[teachersIdArr1.indexOf(ownerTeacherId)]) {
		ownerTeacherName = teachersIdArr[teachersIdArr1.indexOf(ownerTeacherId)][0];
	}
	//console.log("ownerTeacherName:",ownerTeacherName);

	var self = this;
	self.subsubjectOptionalGroup = ko.observable(subsubjectOptionalGroup);
	self.isSubsubject = ko.observable(isSubsubject);
	self.isSubjectOptional = ko.observable(myOptionalStr);
	//console.log(subjectTitle," vvv viewSubjectDetail hasSubSubjects :: ", hasSubSubjects);
	self.hasSubSubjects = ko.observable(hasSubSubjects);
	self.ceGradeId = ko.observable(ceGradeId);
	self.subjectId = ko.observable(subjectId);
	self.aypId = ko.observable(aypId);
	self.ownerTeacherName = ko.observable(ownerTeacherName || "").extend({
		required : true
	});
	self.ownerTeacherId = ko.observable(ownerTeacherId);
	self.periodPerWeek = ko.observable(periodPerWeek).extend({
		required : true,
		min : {

			message : 'Enter a valid teaching periods.',
			params : 1

		},
		max : 100
	});
	self.cePeriodPerWeek = ko.observable(cePeriodPerWeek).extend({
		required : true,
		min : {

			message : 'Enter a valid ClassEdge periods.',
			params : 0

		},
		max : 100
	});
	self.labPeriodPerWeek = ko.observable(labPeriodPerWeek).extend({
		required : true,
		min : {

			message : 'Enter a valid teaching Lab.',
			params : 0

		},
		max : 100
	});
	self.subjectTitle = ko.observable(subjectTitle);
	self.subType = ko.observable(subType);
	self.filteredTeacherArr = ko.observable()
	//self.selectedUserId   								= ko.observable(ownerTeacherId);

	self.cePeriodPerWeek.subscribe(function(newValue) {
		//console.log("cePeriodPerWeek----")
		if (newValue == "") {

			self.cePeriodPerWeek(0);

		}
		var tempCePeriodPerWeekArr = new Array();
		for (var a = 0; a < currViewModel.subjects().length; a++) {
			if (currViewModel.subjects()[a].subsubjectOptionalGroup() != 0) {
				tempCePeriodPerWeekArr.push(a)
			}
		}
		for (var i = 0; i < currViewModel.subjects().length; i++) {
			for (var j = 0; j < tempCePeriodPerWeekArr.length; j++) {
				if (self.subsubjectOptionalGroup() != 0 && currViewModel.subjects()[i].subsubjectOptionalGroup() == currViewModel.subjects()[tempCePeriodPerWeekArr[j]].subsubjectOptionalGroup()) {
					//console.log("Periods will tally",self.periodPerWeek(),currViewModel.subjects()[tempCePeriodPerWeekArr[j]])
					currViewModel.subjects()[tempCePeriodPerWeekArr[j]].cePeriodPerWeek(self.cePeriodPerWeek())
				}
			}

		}
		currViewModel.displayMode(true);
	});
	self.labPeriodPerWeek.subscribe(function(newValue) {
		//console.log("labPeriodPerWeek----")
		if (newValue == "") {

			self.labPeriodPerWeek(0);

		}
		var tempLabPeriodPerWeekArr = new Array();
		for (var a = 0; a < currViewModel.subjects().length; a++) {
			if (currViewModel.subjects()[a].subsubjectOptionalGroup() != 0) {
				tempLabPeriodPerWeekArr.push(a)
			}
		}
		for (var i = 0; i < currViewModel.subjects().length; i++) {
			for (var j = 0; j < tempLabPeriodPerWeekArr.length; j++) {
				if (self.subsubjectOptionalGroup() != 0 && currViewModel.subjects()[i].subsubjectOptionalGroup() == currViewModel.subjects()[tempLabPeriodPerWeekArr[j]].subsubjectOptionalGroup()) {
					//console.log("Periods will tally",self.periodPerWeek(),currViewModel.subjects()[tempPeriodPerWeekArr[j]])
					currViewModel.subjects()[tempLabPeriodPerWeekArr[j]].labPeriodPerWeek(self.labPeriodPerWeek())
				}
			}

		}
		currViewModel.displayMode(true);
	});
	self.periodPerWeek.subscribe(function(newValue) {

		//console.log(self.subjectTitle(), " cc :: periodPerWeek 1 ----newValue :: ", newValue)
		var tempPeriodPerWeekArr = new Array();
		for (var a = 0; a < currViewModel.subjects().length; a++) {
			if (currViewModel.subjects()[a].subsubjectOptionalGroup() != 0) {
				tempPeriodPerWeekArr.push(a)
			}
		}
		//for core subjects
		for (var i = 0; i < currViewModel.subjects().length; i++) {
			for (var j = 0; j < tempPeriodPerWeekArr.length; j++) {
				//console.log(self.subjectTitle(), " :  0  cc subsubjectOptionalGroup() :: ", self.subsubjectOptionalGroup());
				//console.log(" 1 cc subsubjectOptionalGroup() :: ", currViewModel.subjects()[i].subsubjectOptionalGroup());
				//console.log(" 2 cc subsubjectOptionalGroup() :: ", currViewModel.subjects()[tempPeriodPerWeekArr[j]].subsubjectOptionalGroup());

				if (self.subsubjectOptionalGroup() != 0 && currViewModel.subjects()[i].subsubjectOptionalGroup() == currViewModel.subjects()[tempPeriodPerWeekArr[j]].subsubjectOptionalGroup()) {
					//console.log(self.subjectTitle(), " nnn :: periodPerWeek 1 ----newValue :: ", newValue, currViewModel.subjects()[tempPeriodPerWeekArr[j]].subjectTitle())
					//console.log("nnn Periods will tally", self.periodPerWeek(), currViewModel.subjects()[tempPeriodPerWeekArr[j]])
					/**
					 * Prasanna caught 1
					 * Hope: set for same in optionals
					 */
					currViewModel.subjects()[tempPeriodPerWeekArr[j]].periodPerWeek(self.periodPerWeek())
				}
			}

		}

		/**

		 subsubjectOptionalGroup,
		 isSubsubject,
		 hasSubSubjects,
		 ceGradeId,
		 subjectId,
		 subjectTitle,
		 aypId,
		 ownerTeacherName,
		 ownerTeacherId,
		 periodPerWeek,
		 cePeriodPerWeek,
		 labPeriodPerWeek,
		 subType

		 */

		//for Co-Curricular subjects
		//console.log("currViewModel.subjects().length :: ", currViewModel.subjects().length);
		console.log(self.subjectTitle(), " :: subjectTitle : self.isSubjectOptional() :: ", self.isSubjectOptional());
		for (var i = 0; i < currViewModel.subjects().length; i++) {
			var currentSubject = currViewModel.subjects()[i];

			if (currentSubject.subType() == 3 && self.subType() == 3 && currentSubject.isSubjectOptional() && self.isSubjectOptional()) {
				console.log("currentSubject periodPerWeek newValue isSubjectOptional() :: ", currentSubject.periodPerWeek(), newValue, currentSubject.isSubjectOptional(), currentSubject.subjectTitle());
				//console.log(" : if currentSubject.subType() myOptionalStr :: ", currentSubject.subType(), myOptionalStr, currentSubject.subjectTitle());
				if (currentSubject.subjectId() != self.subjectId()) {
					console.log("periodPerWeek change the others value of periods to new one  :: but not the same as it may fire the subscribe again and go to recursive");
					currentSubject.periodPerWeek(newValue);
				};
			};
		}
		console.log("ccc --------------------------------------- :: ");

		currViewModel.displayMode(true);

	});
	self.ownerTeacherName.subscribe(function(newValue) {
		currViewModel.displayMode(true);
	});

	self.changeTeacherModel = ko.computed(function(item) {
		currCeGradeId = self.ceGradeId();
		currSubjectId = self.subjectId();
		//self.teacherNameVal(item.teacherName())
		var _filteredData
		var baseurl = $('#baseUrl').val().split("DUMMY")[0];
		var currSectionId = $("#sectionId").val()
		var AYP_GET_SUBJECT_TEACHER_BY_SEC_GRADE = 'getSubjectTeachersBySecGrade';
		var filteredTeacherUrl = baseurl + AYP_GET_SUBJECT_TEACHER_BY_SEC_GRADE + '&sectionId=' + currSectionId;
		var filteredTeacherDataUrl = filteredTeacherUrl + "&ceGradeId=" + currCeGradeId + "&subjectId=" + currSubjectId;
		var filteredTeacherData = $.getJSON(filteredTeacherDataUrl, {
			returnformat : 'json'
		}, function(teacherData) {
			var mappedfilteredTeacherData = jQuery.map(teacherData, function(item) {
				return new FilteredTeacherVo(item)
				//console.log("filteredTeacherData----------",item)
			});
			self.filteredTeacherArr(mappedfilteredTeacherData);
			_filteredData = mappedfilteredTeacherData
			//console.log("filteredTeacherList----------",self.filteredTeacherArr())

		});
		filteredTeacherData.done(function() {// //console.log( "second success filteredTeacherData" )
		})
		filteredTeacherData.fail(function() {//console.log( "error filteredTeacherData" )
		})
		filteredTeacherData.always(function() {// //console.log( "--mappedPlanData complete--filteredTeacherData" )
		});

		//	$( "#assign-roll" ).dialog( "open" );

		return _filteredData;
	}, this);

	// //console.log("filteredTeacherData----------",self.filteredTeacherArr())

}

function FilteredTeacherVo(data) {
	var self = this;
	self.userId = ko.observable(data.userId);
	self.title = ko.observable(data.title);
	self.firstName = ko.observable(data.firstName);
	self.middleName = ko.observable(data.middleName);
	self.lastName = ko.observable(data.lastName);

	self.fullName = ko.computed(function() {

		var _fullName = self.title() + " " + self.firstName() + " " + self.lastName();
		return _fullName;
	}, this);

}

function viewTempDetail(subsubjectOptionalGroup, isSubsubject, hasSubSubjects, ceGradeId, subjectId, subjectTitle, aypId, ownerTeacherName, ownerTeacherId, periodPerWeek, cePeriodPerWeek, labPeriodPerWeek, subType) {

	var self = this;
	self.subsubjectOptionalGroup = subsubjectOptionalGroup
	self.isSubsubject = isSubsubject
	//console.log(subjectTitle, " vvv viewTempDetail hasSubSubjects :: ", hasSubSubjects);
	self.hasSubSubjects = hasSubSubjects;
	self.ceGradeId = ceGradeId
	self.subjectId = subjectId;
	self.aypId = aypId;
	self.ownerTeacherName = ownerTeacherName;
	self.ownerTeacherId = ownerTeacherId;
	self.periodPerWeek = periodPerWeek;
	self.cePeriodPerWeek = cePeriodPerWeek;
	self.labPeriodPerWeek = labPeriodPerWeek;
	self.subjectTitle = subjectTitle;
	self.subType = subType;
}

function saveUserData() {

	//console.log("------->");
}

// Activates knockout.js
function addclickHandlers(currViewMod) {
	console.log("addclickHandlers currViewMod :: ", currViewMod);
	jQuery("#saveButton").css("opacity", "1");
	jQuery("#saveButton").attr("href", "#");
	//$(selector).attr(attribute)
	jQuery("#saveButton").click(function(event) {
		console.log("event :: ", event);
		currViewMod.saveData();
	});
	jQuery("#cancelButton").click(function(event) {
		//event.preventDefault();
		//console.log("=============", event.target)
		currViewMod.backToAcademicYear();
	});
}

function removeclickHandlers() {
	//jQuery( "#saveButton" ).unbind('click');
	//jQuery( "#saveButton" ).removeAttr("href");
	//jQuery( "#saveButton" ).css("opacity","0.5");
}

head(function() {
	//$(function() {
	//console.log("init called");
	url = jQuery('#baseUrl').val().replace("DUMMY", "");
	aypId = jQuery('#aypId').val();
	sectionId = jQuery('#sectionId').val();
	planStatus = jQuery('#planStatus').val();
	//console.log("url:", url);
	//console.log("aypId:", aypId);
	//console.log("sectionId:", sectionId);
	//console.log("planStatus:", planStatus);
	if (planStatus == 1) {
		jQuery("#buttonsContainer").css("display", "none");
	} else {
		jQuery("#buttonsContainer").css("display", "block");
	}
	// jQuery( "#buttonsContainer" ).css("display","block");
	ko.bindingHandlers.jqAuto = {
		init : function(element, valueAccessor, allBindingsAccessor, viewModel) {
			//console.log("-------> auto complete ");
			$(element).autocomplete({
				source : availableTags,
				select : function(event, ui) {
					$(element).val(ui.item.value).change();
				}
			});
		}
	}
	currViewModel = new curriculamModel();
	currViewModel.sectionTitle(jQuery('#sectionTitle').val());
	addclickHandlers(currViewModel);
	removeclickHandlers();
	ko.applyBindings(currViewModel);
	currViewModel.selectedGrade.subscribe(function(newValue) {
		//console.log("currViewModel.gradeArr", currViewModel.gradeArr());
		//console.log("currViewModel.selectedGrade", newValue);
		if (prevGrade != -1) {
			//console.log("saveTempData called from here");
			saveTempData(currViewModel, prevGrade)
		}
		prevGrade = newValue;
		var ceId = Number(currViewModel.gradeArr.indexOf(newValue));

		//console.log("ceId Vikash - ", ceId, displayArr)

		var disCurr = false;
		if (displayArr[ceId]) {
			if (displayArr[ceId] != "#") {
				currViewModel.subjects.removeAll();
				//console.log("coming here", displayArr[ceId].length)
				if (displayArr[ceId].length < 1) {
					//alert("No data found")
				}
				for (var j = 0; j < displayArr[ceId].length; j++) {

					var myOptionalStr = "";
					if (displayArr[ceId]) {
						myOptionalStr = displayArr[ceId].isOptional;
					} else {
						myOptionalStr = "1 isOptional check head j isOptional: no data";
					};

					console.log("1111111 myOptionalStr :: ", myOptionalStr);
					//1 newviewSubjectDetail
					currViewModel.subjects.push(new viewSubjectDetail(myOptionalStr, displayArr[ceId][j].subsubjectOptionalGroup, displayArr[ceId][j].isSubsubject, displayArr[ceId][j].hasSubSubjects, displayArr[ceId][j].ceGradeId, displayArr[ceId][j].subjectId, displayArr[ceId][j].subjectTitle, displayArr[ceId][j].aypId, displayArr[ceId][j].ownerTeacherName, displayArr[ceId][j].ownerTeacherId, displayArr[ceId][j].periodPerWeek, displayArr[ceId][j].cePeriodPerWeek, displayArr[ceId][j].labPeriodPerWeek, displayArr[ceId][j].subType));
					if (displayArr[ceId][j].subType == 3) {
						disCurr = true;
					}
				}
			} else {
				getCurriculamPlan(ceGradeIdArr[ceId], currViewModel);
			}
		} else {
			getCurriculamPlan(ceGradeIdArr[ceId], currViewModel);
		}
		if (disCurr) {
			jQuery("#coheader").css("display", "block");
			jQuery(".gradeData1").css("display", "block");
		} else {
			jQuery("#coheader").css("display", "none");
			jQuery(".gradeData1").css("display", "none");
		}
	});
	showLoader(true, TYPE_LOADING);
	getSchoolTeachers(availableTags);
	getInitialData(currViewModel);

	ko.bindingHandlers.jqAuto = {
		init : function(element, valueAccessor, allBindingsAccessor, viewModel) {
			$(element).focus(function() {

				prevValue = $(this).val();
			});

			$(element).autocomplete({
				source : availableTags,

				select : function(event, ui) {
					$(element).val(ui.item.value).change();
					prevValue = ui.item.value;

					for (var i = 0; i < currViewModel.subjects().length; i++) {

						var indx = availableTags.indexOf(currViewModel.subjects()[i].ownerTeacherName());
						if (indx != -1) {

							currViewModel.subjects()[i].ownerTeacherId = ko.observable(teachersIdArr[indx][1]);
						}
					}
					valueSelected = true;
				},

				change : function(event, ui) {
					if (!valueSelected) {
						$(element).val(prevValue).change();
					}
					valueSelected = false;
				}
			});
		}
	}

	$("#dialog-alert").dialog({
		autoOpen : false,
		width : 420,
		modal : true,
		show : {
			effect : "blind",
			duration : 0
		},
		hide : {
			effect : "clip",
			duration : 0
		}
	});

	$("#abc").click(function(event) {
		event.preventDefault();
		jQuery("#dialog-alert").dialog("close");
	});

});
function openAlertBox(str) {
	//questModel.alertText(str);
	jQuery("#dialog-alert p").text(str)
	var alertDialog = jQuery("#dialog-alert").dialog("open");
	alertDialog.dialog("option", "position", "center");

}

function displayData(subjectJsonData, currViewModel) {
	currViewModel.subjects.removeAll();
	var subType = "core";
	var displayCurrSub = false;

	//var subsubjectOptionalGroup = 100
	//var subjectType3OptionalGroup = 200
	for (var i = 0; i < subjectJsonData.length; i++) {

		//   //console.log("AAAAAAAAAA=====================",subjectJsonData[i].subSubjects.length);
		// if(subjectJsonData[i].subSubjects.length>0 && subjectJsonData[i].isOptional)//Commentted By Vikash Bhardwaj 16/10/2013
		//{
		var myDispOptionalStr = "2 isOptional check displayData i isOptional :: " + subjectJsonData[i].isOptional;
		var myOptionalStr = subjectJsonData[i].isOptional;

		if (subjectJsonData[i].subjectType == "3") {
			displayCurrSub = true;
			//2 newviewSubjectDetail
			currViewModel.subjects.push(new viewSubjectDetail(myOptionalStr, 0, 0, 1, subjectJsonData[i].ceGradeId, subjectJsonData[i].subjectId, subjectJsonData[i].subjectTitle, subjectJsonData[i].aypId, "abc", subjectJsonData[i].ownerTeacherId, subjectJsonData[i].periodPerWeek, subjectJsonData[i].cePeriodPerWeek, subjectJsonData[i].labPeriodPerWeek, subjectJsonData[i].subjectType));
		} else {
			if (subjectJsonData[i].subSubjects.length > 0) {
				if (subjectJsonData[i].isOptional) {
					//3 newviewSubjectDetail
					currViewModel.subjects.push(new viewSubjectDetail(myOptionalStr, 0, 0, -1, subjectJsonData[i].ceGradeId, subjectJsonData[i].subjectId, subjectJsonData[i].subjectTitle, subjectJsonData[i].aypId, subjectJsonData[i].ownerTeacherName, subjectJsonData[i].ownerTeacherId, subjectJsonData[i].periodPerWeek, subjectJsonData[i].cePeriodPerWeek, subjectJsonData[i].labPeriodPerWeek, subjectJsonData[i].subjectType));
				} else {
					//4 newviewSubjectDetail
					currViewModel.subjects.push(new viewSubjectDetail(myOptionalStr, 0, 0, 1, subjectJsonData[i].ceGradeId, subjectJsonData[i].subjectId, subjectJsonData[i].subjectTitle, subjectJsonData[i].aypId, subjectJsonData[i].ownerTeacherName, subjectJsonData[i].ownerTeacherId, subjectJsonData[i].periodPerWeek, subjectJsonData[i].cePeriodPerWeek, subjectJsonData[i].labPeriodPerWeek, subjectJsonData[i].subjectType));
				}
			} else {

				//5 newviewSubjectDetail
				currViewModel.subjects.push(new viewSubjectDetail(myOptionalStr, 0, 0, 0, subjectJsonData[i].ceGradeId, subjectJsonData[i].subjectId, subjectJsonData[i].subjectTitle, subjectJsonData[i].aypId, subjectJsonData[i].ownerTeacherName, subjectJsonData[i].ownerTeacherId, subjectJsonData[i].periodPerWeek, subjectJsonData[i].cePeriodPerWeek, subjectJsonData[i].labPeriodPerWeek, subjectJsonData[i].subjectType));

			}

		}

		//subsubjectOptionalGroup ++;
		//subjectType3OptionalGroup ++;

		for (var j = 0; j < subjectJsonData[i].subSubjects.length; j++) {
			var myDispOptionalStr = "3 isOptional check displayData j isOptional: " + subjectJsonData[i].isOptional;
			var myOptionalStr = subjectJsonData[i].subSubjects[j].isOptional;
			//console.log("-------subjectJsonData[i]-------------", subjectJsonData[i].subjectTitle)
			if (subjectJsonData[i].subSubjects[j].subjectType == "3") {
				displayCurrSub = true;

				if (subjectJsonData[i].isOptional) {
					//6 newviewSubjectDetail
					currViewModel.subjects.push(new viewSubjectDetail(myOptionalStr, subjectJsonData[i].subjectTitle, 1, 0, subjectJsonData[i].subSubjects[j].ceGradeId, subjectJsonData[i].subSubjects[j].subjectId, subjectJsonData[i].subSubjects[j].subjectTitle, subjectJsonData[i].subSubjects[j].aypId, "abc", subjectJsonData[i].subSubjects[j].ownerTeacherId, subjectJsonData[i].subSubjects[j].periodPerWeek, subjectJsonData[i].subSubjects[j].cePeriodPerWeek, subjectJsonData[i].subSubjects[j].labPeriodPerWeek, subjectJsonData[i].subSubjects[j].subjectType));
					//subjectType3OptionalGroup = -1
				} else {
					//7 newviewSubjectDetail
					currViewModel.subjects.push(new viewSubjectDetail(myOptionalStr, 0, 1, 0, subjectJsonData[i].subSubjects[j].ceGradeId, subjectJsonData[i].subSubjects[j].subjectId, subjectJsonData[i].subSubjects[j].subjectTitle, subjectJsonData[i].subSubjects[j].aypId, "abc", subjectJsonData[i].subSubjects[j].ownerTeacherId, subjectJsonData[i].subSubjects[j].periodPerWeek, subjectJsonData[i].subSubjects[j].cePeriodPerWeek, subjectJsonData[i].subSubjects[j].labPeriodPerWeek, subjectJsonData[i].subSubjects[j].subjectType));
				}

			} else {
				//console.log("SubSubjectList----------", subjectJsonData[i].subSubjects)
				if (subjectJsonData[i].isOptional) {
					//8 newviewSubjectDetail
					currViewModel.subjects.push(new viewSubjectDetail(myOptionalStr, subjectJsonData[i].subjectTitle, 1, 0, subjectJsonData[i].subSubjects[j].ceGradeId, subjectJsonData[i].subSubjects[j].subjectId, subjectJsonData[i].subSubjects[j].subjectTitle, subjectJsonData[i].subSubjects[j].aypId, subjectJsonData[i].subSubjects[j].ownerTeacherName, subjectJsonData[i].subSubjects[j].ownerTeacherId, subjectJsonData[i].subSubjects[j].periodPerWeek, subjectJsonData[i].subSubjects[j].cePeriodPerWeek, subjectJsonData[i].subSubjects[j].labPeriodPerWeek, subjectJsonData[i].subSubjects[j].subjectType));
					//subsubjectOptionalGroup = -1
				} else {
					//9 newviewSubjectDetail
					currViewModel.subjects.push(new viewSubjectDetail(myOptionalStr, 0, 1, 0, subjectJsonData[i].subSubjects[j].ceGradeId, subjectJsonData[i].subSubjects[j].subjectId, subjectJsonData[i].subSubjects[j].subjectTitle, subjectJsonData[i].subSubjects[j].aypId, subjectJsonData[i].subSubjects[j].ownerTeacherName, subjectJsonData[i].subSubjects[j].ownerTeacherId, subjectJsonData[i].subSubjects[j].periodPerWeek, subjectJsonData[i].subSubjects[j].cePeriodPerWeek, subjectJsonData[i].subSubjects[j].labPeriodPerWeek, subjectJsonData[i].subSubjects[j].subjectType));
				}
			}
		}

	}
	if (displayCurrSub) {
		//console.log("What is this cocurr true", jQuery("#coheader"))
		jQuery("#coheader").css("display", "block");
		jQuery(".gradeData1").css("display", "block");
	} else {
		//console.log("What is this cocurr", jQuery("#coheader"))
		jQuery("#coheader").css("display", "none");
		jQuery(".gradeData1").css("display", "none");
	}

	//console.log(" ::: ",currViewModel.subjects())
}

function getInitialData(currViewModel) {
	currViewModel.gradeArr.removeAll();
	$.ajax({
		url : url + "getSectionClassesBYSection",
		type : "post",
		data : {
			sectionId : sectionId,
			aypId : aypId
		},
		success : function(result) {
			//console.log("Initial data", result);
			for (var i = 0; i < result.length; i++) {
				ceGradeIdArr.push(result[i].ceGradeId)
				currViewModel.gradeArr.push({
					gradeName : result[i].gradeTitle
				});
				displayArr.push("#");
				if (i == result.length - 1) {
					//console.log("coming here for sorting");

					// Commented by Vikash Bhardwaj 08-10-2013
					/*	currViewModel.gradeArr.sort(function(item1, item2) {

					 if (item1.gradeName> item2.gradeName) {
					 return 1;
					 } else if(item1.gradeName< item2.gradeName) {
					 return -1;
					 } else {
					 return 0;
					 }

					 });*/

					currViewModel.selectedGrade(currViewModel.gradeArr()[0]);
					//console.log("currViewModel.selectedGrade======", currViewModel.selectedGrade(), currViewModel.gradeArr()[0].gradeName);
				}

				getCurriculamPlan(result[0].ceGradeId, currViewModel);
			}
			//getNoOfPeriods(result[0].ceGradeId);
		},
		error : function(jqXHR, textStatus, errorThrown) {
			//console.log("error");
		}
	});

}

function getCurriculamPlan(ceGradeId, currViewModel) {
	//console.log("#getCurriculamPlan#getSectionCurrPlans#ceGradeId", ceGradeId);
	$.ajax({
		url : url + "getSectionCurrPlans",
		type : "post",
		data : {
			ceGradeId : ceGradeId,
			aypId : aypId,
			sectionId : sectionId
		},
		success : function(result) {
			//console.log("Data from server to display", result);
			displayData(result, currViewModel);
			getNoOfPeriods(ceGradeId, currViewModel)
			showLoader(false);
		},
		error : function(jqXHR, textStatus, errorThrown) {
			//console.log("error");
		}
	});
}

function saveDataToServer(savedata) {
	//console.log("BO saveDataToServer savedata ::\n ", savedata);
	//console.log("\n EO saveDataToServer savedata :: ");
	$.ajax({
		url : url + "saveSectionCurrPlans",
		type : "post",
		data : {
			savedata : savedata
		},
		success : function(result) {
			console.log("data to server", result);
			showLoader(false);
		},

		error : function(jqXHR, textStatus, errorThrown) {
			console.log("error");
		}
	});
}

function saveTempData(currView, currGrade) {
	//console.log("saveTempData function called===============", displayArr)
	tempArray = new Array();
	for (var p = 0; p < currView.subjects().length; p++) {
		var hasSubSubjects = currView.subjects()[p].hasSubSubjects();
		var isSubsubject = currView.subjects()[p].isSubsubject();
		var subsubjectOptionalGroup = currView.subjects()[p].subsubjectOptionalGroup();

		var ceGradeId = currView.subjects()[p].ceGradeId();
		var subjectId = currView.subjects()[p].subjectId();
		var subjectTitle = currView.subjects()[p].subjectTitle();
		var aypId = currView.subjects()[p].aypId();
		var ownerTeacherName = currView.subjects()[p].ownerTeacherName();
		var ownerTeacherId = currView.subjects()[p].ownerTeacherId();
		var periodPerWeek = currView.subjects()[p].periodPerWeek();
		var cePeriodPerWeek = currView.subjects()[p].cePeriodPerWeek();
		var labPeriodPerWeek = currView.subjects()[p].labPeriodPerWeek();
		var subType = currView.subjects()[p].subType();
		//console.log(subjectTitle," vvv saveTempData hasSubSubjects :: ", currView.subjects()[p].hasSubSubjects());
		tempArray.push(new viewTempDetail(subsubjectOptionalGroup, isSubsubject, hasSubSubjects, ceGradeId, subjectId, subjectTitle, aypId, ownerTeacherName, ownerTeacherId, periodPerWeek, cePeriodPerWeek, labPeriodPerWeek, subType))
	}
	//console.log("whats ======", currGrade)
	var ceId = Number(currView.gradeArr.indexOf(currGrade));

	if (displayArr[ceId]) {
		displayArr[ceId] = tempArray;

	} else {
		displayArr.push(tempArray);
	}
	//console.log("saveTempData function called===============after", displayArr);
}

function getSchoolTeachers() {
	availableTags = new Array();
	$.ajax({
		url : url + "getSchoolTeachers",
		type : "post",

		success : function(result) {
			//console.log("teachers data", result);
			for (var i = 0; i < result.length; i++) {
				var fullName = result[i].firstName + " " + result[i].lastName
				availableTags.push(fullName);
				teachersIdArr.push([fullName, result[i].userId])
				teachersIdArr1.push(result[i].userId);
			}
			//console.log("teachers information", teachersIdArr);

		},
		error : function(jqXHR, textStatus, errorThrown) {
			//console.log("error");
		}
	});
}

function getNoOfPeriods(ceGradeId, currViewModel) {
	var fullUrl = url + "getNoOfPeriodsPerSecGrade&sectionId=" + sectionId + "&ceGradeId=" + ceGradeId;
	//console.log("fullUrl getNoOfPeriodsPerSecGrade:: ",fullUrl);
	$.ajax({
		url : url + "getNoOfPeriodsPerSecGrade",
		type : "post",
		data : {
			sectionId : sectionId,
			ceGradeId : ceGradeId
		},
		success : function(result) {
			//console.log("Total periods", result);
			currViewModel.totalAcademicPeriods(result);
		},
		error : function(jqXHR, textStatus, errorThrown) {
			//console.log("error");
		}
	});

}

function showHelp() {
	//console.log("-------> showing help dialog", isHelpActive);

	if (!isHelpActive) {
		isHelpActive = true;
		helpType = "ayp_curriculam";
		//var active = jQuery("#tabs").tabs("option", "active");
		//help_scrollPosition = 'ayp_section_' + active;

		jQuery(".help").load("/ce-static-testedge/common/html/help.html", function() {
			//scrollTo('ayp_section_'+active);
			//console.log('ayp_section_' + active);
			//console.log("help called");
		});
		//jQuery(".help").css("display","block");
		// jQuery(".help").css("height","-1px");
	} else {
		isHelpActive = false;
		jQuery(".help").empty();
		//jQuery(".help").css("display","none");
		//jQuery(".help").css("height","-1px");
	}
}

function closeHelpSection() {
	//console.log("closing help section");
	isHelpActive = false;
	//jQuery(".help").css("display","none");
	//jQuery(".help").css("height","-1px");
	jQuery(".help").empty();
}

function success() {
	//console.log("succesfully saved");
}

